import re

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.generics import CreateAPIView,UpdateAPIView, GenericAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import RetrieveAPIView
from users.serializer import RegisterCreateSerializer, UserDetailSerializer,EmailSerializer, UserListSerializer
from . models import User
# Create your views here.

class RegisterUsername(APIView):
    #获取用户名的个数
    #GET请求  /users/users/(?P<username>\w{5,20})/count/
    def get(self,request,username):
        #通过模型类查询，获取用户名个数
        count=User.objects.filter(username=username).count()
        #组织数据
        context={
            'count':count,

        }
        return Response(context)


class RegisterUsermobile(APIView):
    #手机号码
    #GET请求 /users/phones/?P<mobile>1[345789]\d{9})/count/
    def get(self,request,mobile):
        count=User.objects.filter(mobile=mobile).count()
        #数据传递
        context={
            'count':count,
            'mobile':mobile
        }
        return Response(context)




#用户注册
class RegisterCreateView(CreateAPIView):
    #POST/Users
    #用户注册我们需要对数据库校验，入库

    serializer_class =RegisterCreateSerializer
    #进行校验
    #单个字段的校验  手机号码，是否同意协议



class UserDetailView(RetrieveAPIView):
    #获取登录用户的信息
    #get/users/
    #用到权限管理
    #在视图对象获取request.user　　用户信息
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer
    def get_object(self):
        return self.request.user




class EmailView(UpdateAPIView):
    #保存邮件
    #put/users/emails

    permission_classes = [IsAuthenticated]

    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user
class UserListView(GenericAPIView):
    def get_serializer_class(self):
        return UserListSerializer

    def get_queryset(self):
        return User.objects.all()







class VerificationEmailView(APIView):
    #验证激活邮箱
    #get/users/emails/verification/?token=xxx
    '''
    获取ｔｏｋｅｎ　并判断
    获取ｔｏｋｅｎ中的ｉｄ
    查询用户，并判断是否存在
    修改状态
    返回响应
    '''
    def get(self,request):
        #获取ｔｏｋｅｎ
        token=request.query_params.get('token')
        print(token)
        if not token:
            return Response({'message':'缺'})
        #获取ｔｏｋｅｎ中ｉｄ，ｅｍａｉｌ
        # 查询用户，判断是否存在
        user=User.check_verify_email_token(token)
        if user is None:
            return Response({'message':'无效链接'})
        else:
            #修改状态
            user.email_active=True
            user.save()
            #返回响应
            return Response({'message':'ok'})
